module Queue.SimpleQueueLen (Queue,
                       isEmpty,
                       empty,
                       add,
                       head,
                       tail) where

import Prelude hiding (head, tail)

data Queue a = Queue{left::[a], lenLeft::Int, right::[a], lenRight::Int}

isEmpty Queue{left=[]} = True
isEmpty _ = False

empty = Queue [] 0 [] 0

add q@Queue{right=xs,lenRight=lr} x = norm q{right=x:xs,lenRight=lr+1}

head Queue{left=x:_} = x
head Queue{left=[]} = error "head on empty queue"

tail q@Queue{left=_:xs,lenLeft=ll} = norm q{left=xs,lenLeft=ll-1}
tail Queue{left=[]} = error "tail on empty queue"

norm q@Queue{left=xs,lenLeft=ll,right=ys,lenRight=lr} =
  if lr > ll then
    Queue (xs++reverse ys) (ll+lr) [] 0
  else q
